#include <stdio.h>
#include <string.h>
#include <time.h>

#include <global/types.h>
#include <global/const.h>
#include <utils/string.h>
#include <utils/datetime.h>

char * dt_snow(const char * fmt)
{
	static char now[MAXDATETIME];
	static time_t t;
	static struct tm * m;

	bzero(now, MAXDATETIME);

	t = time(NULL);
	m = localtime(&t);

	strftime(now, MAXDATETIME, fmt, m);

	return now;
}

char * dt_sfmt(time_t * pt, const char * fmt)
{
	static char ret[MAXDATETIME];
	static struct tm * m;

	bzero(ret, MAXDATETIME);
	
	m = localtime(pt);
	strftime(ret, MAXDATETIME, fmt, m);

	return ret;
}

time_t dt_stot(const char * s)
{
	static struct tm m;
	static int sl;
	time_t t;

	bzero(&m, sizeof(struct tm));

	sl = strlen(s);

	if (sl >= 4 && sl % 2 == 0)
	{
		m.tm_year = atoi(st_lsub(s, 4)) - 1900;
		m.tm_mon = sl >= 6 ? atoi(st_lsub(s + 4, 2)) - 1 : 0; // month [0-11]
		m.tm_mday = sl >= 8 ? atoi(st_lsub(s + 6, 2)) : 0;
		m.tm_hour = sl >= 10 ? atoi(st_lsub(s + 8, 2)) : 0;
		m.tm_min = sl >= 12 ? atoi(st_lsub(s + 10, 2)) : 0;
		m.tm_sec = sl >= 14 ? atoi(st_lsub(s + 12, 2)) : 0;
	}

	return mktime(&m);
}
